package com.sunchangpeng.command;

import java.io.*;

public class StreamGobbler extends Thread {
    private static final byte[] BYTES_NEW_LINE = "\n".getBytes();

    protected final InputStream is;
    protected final String prefix;
    protected final OutputStream out;
    protected final Object lock = new Object();
    protected boolean end = false;

    public StreamGobbler(final InputStream is) {
        this(is, null, null);
    }

    public StreamGobbler(final InputStream is, final OutputStream output) {
        this(is, output, null);
    }

    public StreamGobbler(final InputStream is, final OutputStream output, final String prefix) {
        this.is = is;
        this.prefix = prefix;
        this.out = output;
    }

    @Override
    public void run() {
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);

        try {
            String line;
            while ((line = br.readLine()) != null) {
                if (out != null) {
                    if (prefix != null) {
                        out.write(prefix.getBytes());
                    }
                    out.write(line.getBytes());
                    out.write(BYTES_NEW_LINE);
                }
            }
        } catch (IOException ioe) {
            if (out != null) {
                ioe.printStackTrace(new PrintStream(out));
            }
        } finally {
            if (out != null) {
                try {
                    out.flush();
                } catch (IOException ignore) {
                }
            }
            try {
                br.close();
            } catch (IOException ignore) {
            }
        }

        synchronized (lock) {
            lock.notifyAll();
            end = true;
        }
    }

    /**
     * Waits for gobbler to end.
     */
    public void waitFor() {
        try {
            synchronized (lock) {
                if (!end) {
                    lock.wait();
                }
            }
        } catch (InterruptedException ignore) {
            Thread.currentThread().interrupt();
        }
    }

}